package com.leadbank.security.hello.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;

import java.sql.Connection;
import java.util.Properties;

/**
 * Created by hp on 2018/11/30.
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class})})
public class DeleteWarningPlugin implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        System.out.println();
        if ("DELETE".equals(ms.getSqlCommandType().name())) {
            SqlSource sqlSource = ms.getSqlSource();
            if(sqlSource instanceof RawSqlSource) {
                RawSqlSource rawSqlSource = (RawSqlSource) sqlSource;
                MetaObject metaObject = SystemMetaObject.forObject(rawSqlSource);
                SqlSource thisSqlSource = (SqlSource) metaObject.getValue("sqlSource");
                MetaObject metaObjectSql = SystemMetaObject.forObject(thisSqlSource);
                String sql = (String) metaObjectSql.getValue("sql");
                System.out.println("系统发生删除操作：" + sql);
            } else if(sqlSource instanceof DynamicSqlSource) {
                DynamicSqlSource dynamicSqlSource = (DynamicSqlSource) sqlSource;
                BoundSql boundSql = dynamicSqlSource.getBoundSql(invocation.getArgs()[1]);
                String sql = boundSql.getSql();
                System.out.println("系统发生删除操作：" + sql);
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        for (String key : properties.stringPropertyNames()) {
            System.out.println(key + " " + properties.get(key));
        }
    }
}
